import React, { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import { Spin, Empty, message, Skeleton } from 'antd';
import { hotRadarService } from '../../../services/hotRadar.service';
import { HotItemTrend } from '../../../types/hotRadar';
import ErrorBoundary from '../../common/ErrorBoundary';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { useViewport } from '../../../hooks/useViewport';
import './style.css';

interface HeatTrendChartProps {
  itemId: string;
}

const HeatTrendChartCore: React.FC<HeatTrendChartProps> = ({ itemId }) => {
  const [loading, setLoading] = useState(false);
  const [trendData, setTrendData] = useState<HotItemTrend[]>([]);
  const breakpoint = useBreakpoint();
  const viewport = useViewport();
  const isMobile = breakpoint === 'mobile';

  useEffect(() => {
    fetchTrendData();
  }, [itemId]);

  const fetchTrendData = async () => {
    setLoading(true);
    try {
      const data = await hotRadarService.getHotItemTrends(itemId);
      setTrendData(data);
    } catch (error) {
      message.error('获取趋势数据失败');
      console.error('Failed to fetch trend data:', error);
    } finally {
      setLoading(false);
    }
  };

  const getChartOption = () => {
    if (!trendData || trendData.length === 0) {
      return null;
    }

    const timestamps = trendData.map((item) =>
      new Date(item.timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
      })
    );

    const heatValues = trendData.map((item) => parseInt(item.heat_value));
    const ranks = trendData.map((item) => item.rank);

    // 响应式字体大小
    const baseFontSize = isMobile ? 12 : 14;
    const legendFontSize = isMobile ? 12 : 14;
    const axisFontSize = isMobile ? 10 : 12;
    const titleFontSize = isMobile ? 12 : 14;

    return {
      // 移动端优化的 tooltip
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        textStyle: {
          fontSize: isMobile ? 12 : 14,
        },
        // 移动端触摸优化
        triggerOn: isMobile ? 'click' : 'mousemove|click',
        confine: true, // 限制在图表区域内
      },
      // 响应式图例
      legend: {
        data: ['热度值', '排名'],
        bottom: 0,
        textStyle: {
          fontSize: legendFontSize,
        },
        // 移动端图例可能需要调整位置
        itemGap: isMobile ? 10 : 20,
      },
      // 响应式网格布局
      grid: {
        left: isMobile ? 40 : 60,
        right: isMobile ? 40 : 60,
        top: isMobile ? 40 : 60,
        bottom: isMobile ? 80 : 80,
        containLabel: true,
      },
      // 移动端触摸缩放和拖拽
      dataZoom: isMobile ? [
        {
          type: 'inside', // 触摸内部缩放
          start: 0,
          end: 100,
          zoomOnMouseWheel: false,
          moveOnMouseMove: true,
        },
      ] : undefined,
      // 工具栏配置
      toolbox: isMobile ? undefined : {
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          restore: {},
          saveAsImage: {},
        },
        right: 20,
        top: 10,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: timestamps,
        axisLabel: {
          rotate: isMobile ? 45 : 30,
          fontSize: axisFontSize,
          // 移动端减少显示标签数量
          interval: isMobile ? 'auto' : 0,
        },
        axisLine: {
          lineStyle: {
            width: isMobile ? 1 : 1,
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '热度值',
          nameTextStyle: {
            fontSize: titleFontSize,
          },
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#ff4d4f',
              width: isMobile ? 1 : 2,
            },
          },
          axisLabel: {
            fontSize: axisFontSize,
            formatter: (value: number) => {
              if (value >= 100000000) {
                return `${(value / 100000000).toFixed(1)}亿`;
              }
              if (value >= 10000) {
                return `${(value / 10000).toFixed(0)}万`;
              }
              return value.toString();
            },
          },
          splitLine: {
            lineStyle: {
              type: isMobile ? 'dashed' : 'solid',
              opacity: isMobile ? 0.3 : 0.5,
            },
          },
        },
        {
          type: 'value',
          name: '排名',
          nameTextStyle: {
            fontSize: titleFontSize,
          },
          position: 'right',
          inverse: true,
          min: 1,
          axisLine: {
            lineStyle: {
              color: '#1890ff',
              width: isMobile ? 1 : 2,
            },
          },
          axisLabel: {
            fontSize: axisFontSize,
          },
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: '热度值',
          type: 'line',
          smooth: true,
          yAxisIndex: 0,
          data: heatValues,
          itemStyle: {
            color: '#ff4d4f',
          },
          lineStyle: {
            width: isMobile ? 2 : 3,
          },
          // 移动端使用更小的符号
          symbolSize: isMobile ? 4 : 6,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(255, 77, 79, 0.3)',
                },
                {
                  offset: 1,
                  color: 'rgba(255, 77, 79, 0.05)',
                },
              ],
            },
          },
        },
        {
          name: '排名',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: ranks,
          itemStyle: {
            color: '#1890ff',
          },
          lineStyle: {
            width: isMobile ? 2 : 3,
          },
          symbolSize: isMobile ? 4 : 6,
        },
      ],
      // Canvas 渲染器（移动端性能更好）
      renderer: 'canvas',
    };
  };

  // 响应式图表高度
  const chartHeight = isMobile ? 300 : 400;

  if (loading) {
    return (
      <div className="heat-trend-loading">
        <Skeleton active paragraph={{ rows: 6 }} />
      </div>
    );
  }

  const chartOption = getChartOption();

  if (!chartOption) {
    return <Empty description="暂无趋势数据" />;
  }

  return (
    <div className="heat-trend-chart">
      <ReactECharts
        option={chartOption}
        style={{ height: chartHeight, width: '100%' }}
        notMerge={true}
        lazyUpdate={true}
        opts={{ renderer: 'canvas' }}
      />
    </div>
  );
};

// Export with error boundary wrapper
export const HeatTrendChart: React.FC<HeatTrendChartProps> = (props) => {
  return (
    <ErrorBoundary
      onError={(error, errorInfo) => {
        console.error('Chart rendering error:', error, errorInfo);
        message.error('图表渲染失败，请刷新重试');
      }}
    >
      <HeatTrendChartCore {...props} />
    </ErrorBoundary>
  );
};